package cn.onein.edu.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.onein.edu.biz.bean.User;
import cn.onein.edu.util.StringUtil;
import cn.onein.edu.web.common.base.BaseController;
import cn.onein.edu.web.service.LoginService;

/**
 * 用户记住用户名，密码后的自动登录
 * @author Upton
 *
 */
public class AutoLoginFilter implements Filter{	

	private LoginService loginService;

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {		
		HttpServletRequest request = (HttpServletRequest)req;
		
		HttpSession session = (HttpSession)request.getSession(false);
		boolean successedLogin = false;
		if(session != null){
			User user = (User)session.getAttribute(BaseController.SESSION_USER_KEY);
			if(user != null){
				successedLogin = true;
			}
		}
		
		if(successedLogin == false){
			Cookie[] cookies = request.getCookies();
			if(cookies != null && cookies.length >= 2){
				String userName = null;
				String pass = null;
				for(Cookie cookie : cookies){
					if(BaseController.COOKIE_KEY_USER.equals(cookie.getName())){
						userName = cookie.getValue();
					}
					else if(BaseController.COOKIE_KEY_PASS.equals(cookie.getName())){
						// 经过一次加密的password
						pass = cookie.getValue();
					}
				}
				
				if(userName != null && pass != null){
					String lastIP = request.getRemoteAddr();
					User user = loginService.login(userName,StringUtil.secondMD5(pass), lastIP);
					
					if (user != null) {
						// 设置用户信息
						request.getSession(true).setAttribute(BaseController.SESSION_USER_KEY, user);
					}
				}
			}
		}
		
		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		loginService = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()).getBean("loginServiceImpl", LoginService.class);		
	}	
}
